<?php
// ### AclAssistant : Community

class Action_Community_UpdateUserProfileViaOpenid extends RL_Handler
{
	protected function init() {
		
		$this->acl_assistant = $this->module->aa;
		$this->acl_data = $this->acl_assistant->getInfo();
		$this->acl_assistant->getAvailableOperations();
		
		$this->rh->UseClass("Model_User");
		$this->m_user = new Model_User( $this->rh, $this->acl_assistant);	
	}
	
	public function process ()
	{
		$user_oid = $this->params['user_url'];
		$user_obj = $this->m_user->getUser( $user_oid );
		$user_data = $user_obj->data;
			

		if ($_POST) {
			$auth_input = new RL_Principal_Input_Array(array(
				'openid_url'=>$this->rh->POST['openid_url'],
				'openid_action'=>'login',
			));
		} elseif ($_GET['openid_mode'] == 'id_res') {
			$auth_input = new RL_Principal_Input_Array(array(
				'openid_url'=>$this->rh->POST['openid_url'],
			));
		} else {
			$auth_input = NULL;
		}

		if ($auth_input) {
			require_once 'RL/Principal.php';
			$auth_method = new RL_Principal_Auth_Openid(array(
				'trust_url'  => $this->ctx->rh->base_url,
			));

			if ($cred = $auth_method->identify($auth_input)) {
				$data = $auth_method->getProfile();
				$fields = array(
					'sreg.fullname' => 'fullname',
					'sreg.email'    => 'email',
					'sreg.timezone' => 'timezone',
				);
				$changed = false;
				foreach ($fields as $oname => $dname) {
					if (isset($data['signed'][$oname]) && $data['signed'][$oname]) {
						$user_obj->data[$dname] = $data['signed'][$oname];
						$changed = true;
					}
				}
				
				if (!$changed || $this->m_user->updateUser( $user_obj )) {
					$up_url = $this->rh->base_url;
					if ( isset($this->acl_data['community_url']) ) {
						$up_url .= $this->rh->base_url.$this->acl_data['community_url']."/";
					}
					$up_url .= $this->acl_data['path']."/".$this->acl_data['user_url']."/edit";
					$this->rh->response->setContent("Ваш профиль обновлен");
					$this->rh->redirect($up_url, 3);
				} else {
					echo "some kind of error in updating db entries.";
				}
			} else {
				var_dump( $auth_method->error);
			}
		} else {
			$view = $this->rh->views->findByName('msg');
			$this->rh->response->setContent( $view );
		}
	} // end of function execute

}
